<template>
  <view class="quotation-container">

    
    <!-- 已选中角色展示 -->
    <view class="selected-roles-container" v-if="parsedRoleArr.length > 0">
           <!-- 团队信息 -->
           <view class="profile-form">
            
          <text>填写报价</text>
        <!-- 单人报价 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">单人报价</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="quotationPrice"
              @input="onPriceInput"
              placeholder="请输入"
              maxlength="20"
            />
            <text class="unit-text">/天</text>
          </view>
        </view>
        
        <!-- 总报价 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">总报价</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              :value="totalPrice + '元'"
              maxlength="20"
              readonly
            />
          </view>
        </view>
      </view>
  
    </view>

    <!-- 底部按钮区域 -->
    <view class="footer">
      <view class="cancel-btn" @click="cancelQuotation">
        <text>取消报价</text>
      </view>
      <view class="confirm-btn" @click="confirmQuotation" :class="{ disabled: !quotationPrice }">
        <text>保存报价</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useProjectStore } from '/stores/project.js'
import { useUserStore } from '/pages/store/user.js'
import { apiService } from '/pages/utils/api.js'

const quotationPrice = ref('')
const inputFocus = ref(false)

// 存储传递过来的参数
const pageParams = ref({})
// 解析后的角色数组
const parsedRoleArr = ref([])

// 使用项目store和用户store
const projectStore = useProjectStore()
const userStore = useUserStore()

// 计算总报价（响应式）
const totalPrice = computed(() => {
  const price = parseFloat(quotationPrice.value)
  if (!quotationPrice.value || isNaN(price) || price <= 0) {
    return '0'
  }

  // 总报价 = 单人报价 * 选中人数
  const result = parsedRoleArr.value.length * price
  return result.toString()
})

onLoad((options) => {
  console.log('报价页面加载完成', options)
  
  // 初始化用户状态
  userStore.initUserState()
  
  // 设置导航栏标题
  projectStore.setNavigationTitle()
  
  // 保存传递过来的参数
  pageParams.value = {
    min: options.min || '',
    classify: decodeURIComponent(options.classify || ''),
    projectId: options.projectId || '',
    roleType: options.roleType || '',
    detailsId: options.detailsId || ''

  }
  console.log('接收到的页面参数:', pageParams.value)
  console.log('arr');
  
  
})


// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1
  })
}

// 价格输入处理
const onPriceInput = (e) => {
  let value = e.detail.value
  // 只允许输入数字和小数点，最多两位小数
  value = value.replace(/[^\d.]/g, '')
  if (value.split('.').length > 2) {
    value = value.substring(0, value.lastIndexOf('.'))
  }
  if (value.includes('.')) {
    const parts = value.split('.')
    if (parts[1] && parts[1].length > 2) {
      value = parts[0] + '.' + parts[1].substring(0, 2)
    }
  }
  quotationPrice.value = value
}

// 输入框聚焦
const onInputFocus = () => {
  inputFocus.value = true
}

// 输入框失焦
const onInputBlur = () => {
  inputFocus.value = false
}

// 取消报价
const cancelQuotation = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消报价吗？',
    confirmText: '确定',
    cancelText: '继续报价',
    confirmColor: '#ff6a9c',
    success: (res) => {
      if (res.confirm) {
        goBack()
      }
    }
  })
}

// 保存报价
const confirmQuotation = () => {
  if (!quotationPrice.value) {
    uni.showToast({
      title: '请输入报价金额',
      icon: 'none'
    })
    return
  }

  const price = parseFloat(quotationPrice.value)
  if (price <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '保存报价',
    content: `确认保存报价 ¥${quotationPrice.value}/天 吗？`,
    confirmText: '确认',
    cancelText: '修改',
    confirmColor: '#ff6a9c',
    success: (res) => {
      if (res.confirm) {
        // 保存报价逻辑
        saveQuotation()
        submitQuotation()

      }
    }
  })
}

// 保存报价到本地存储
const saveQuotation = () => {
  // 获取当前项目ID作为存储key的一部分
  const projectId = pageParams.value.projectId
  const detailsId = pageParams.value.detailsId
  const roleType = pageParams.value.roleType
  
  // 构建存储key
  const storageKey = `quotation_${projectId}_${detailsId}_${roleType}`
  
  // 构建保存的数据对象
  const quotationData = {
    price: totalPrice.value, // 总报价
    DetailsId: detailsId, // 需求明细记录id
    roleType: roleType // 角色类型
  }
  
  // 保存到本地存储
  uni.setStorageSync(storageKey, quotationData)
  
  console.log('报价已保存到本地存储:', {
    key: storageKey,
    data: quotationData
  })
  
}

// 获取项目所有保存的报价数据
const getAllProjectQuotations = (projectId) => {
  const quotations = []
  
  // 获取所有本地存储的key
  const storageInfo = uni.getStorageInfoSync()
  
  // 筛选出当前项目的报价数据
  storageInfo.keys.forEach(key => {
    if (key.startsWith(`quotation_${projectId}_`)) {
      const quotationData = uni.getStorageSync(key)
      if (quotationData) {
        quotations.push(quotationData)
      }
    }
  })
  
  return quotations
}

// 清除项目所有保存的报价数据
const clearProjectQuotations = (projectId) => {
  const storageInfo = uni.getStorageInfoSync()
  
  storageInfo.keys.forEach(key => {
    if (key.startsWith(`quotation_${projectId}_`)) {
      uni.removeStorageSync(key)
    }
  })
}

// 提交报价（保留原有方法，供后续使用）
const submitQuotation = async () => {
  uni.showLoading({
    title: '提交中...'
  })

  // 获取当前登录用户的rowid
  const userRowid = userStore.rowid || uni.getStorageSync('rowid')
  
  if (!userRowid) {
    uni.hideLoading()
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.navigateTo({
      url: '/pages/login/login'
    })
    return
  }
  
  // 根据角色类型进行验证
  const classify = pageParams.value.classify || ''
  console.log('提交时的角色类型:', classify)
  console.log('提交时的parsedRoleArr.value:', parsedRoleArr.value)
  console.log('提交时的parsedRoleArr.value.length:', parsedRoleArr.value.length)
  
  if (classify === "一类角色") {
    // 一类角色需要验证角色数组
    if (parsedRoleArr.value.length === 0) {
      uni.hideLoading()
      uni.showToast({
        title: '角色信息错误，请重新选择',
        icon: 'none'
      })
      return
    }
  }
  // 二类角色不需要验证角色数组，直接使用min值
  console.log('提交时的classify:', classify);
  console.log('提交报价参数:', {
    
    roleArr: decodeURIComponent(classify) === "一类角色" ? parsedRoleArr.value : [], // 只有一类角色才传递角色数组
    price: quotationPrice.value, //报价
    // totalPrice: totalPrice.value, // 总价
    rowid: userRowid, // 用户记录id
    projectId: pageParams.value.projectId, // 项目记录id
    DetailsId: pageParams.value.detailsId //  需求明细记录id
  })
  
  const res = await apiService.quotation({
    roleArr: decodeURIComponent(classify) === "一类角色" ? parsedRoleArr.value : [], // 只有一类角色才传递角色数组
    price: quotationPrice.value,
    // totalPrice: totalPrice.value,
    rowid: userRowid,
    projectId: pageParams.value.projectId,
    DetailsId: pageParams.value.detailsId
  })
  
  console.log('API响应结果:', res)
  
  // 隐藏加载提示
  uni.hideLoading()
  
  // 显示成功提示
  uni.showToast({
    title: '报价提交成功',
    icon: 'success',
    duration: 2000
  })
  
  // 显示加载中提示，覆盖等待期间
  uni.showLoading({
    title: '正在同步，请稍候...',
    mask: true
  })
  
  // 1~2秒后回退并刷新position页面（优化响应速度）
  const delay = 1000 + Math.floor(Math.random() * 1000)
  setTimeout(() => {
    const projectId = pageParams.value.projectId
    const classify = decodeURIComponent(pageParams.value.classify || '')

    // 设置刷新标记（position.vue 在 onShow 中读取并刷新）
    uni.setStorageSync('refreshPositionProjectId', projectId)

    // 动态回退层级：一类角色默认回退3层；二类角色默认回退1层
    const defaultDelta = classify === '一类角色' ? 3 : 1
    try {
      const pages = getCurrentPages && getCurrentPages()
      if (pages && pages.length > 1) {
        const delta = Math.min(defaultDelta, pages.length - 1)
        // 关闭加载提示后再回退
        uni.hideLoading()
        uni.navigateBack({ delta })
        return
      }
    } catch (e) {
      // ignore
    }

    // 兜底：如果无法回退，则直接打开position页
    uni.hideLoading()
    uni.redirectTo({
      url: `/pages/tabs/project/detail/position?id=${projectId}`
    })
  }, delay)
}


</script>

<style lang="scss" scoped>

.profile-form {
  background-color: #fff;
  border-radius: 16rpx;
  margin-top: 10rpx;
}
.form-item {
  margin-top: 10rpx;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.avatar-item {
    align-items: flex-start;
    padding: 30rpx 0;
  }
}

.item-label {
  flex-shrink: 0;
  width: 160rpx;
}

.label-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.input-container {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  justify-content: flex-end;
}

.input-field {
  width: 200rpx;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
  text-align: right;
  
  &::placeholder {
    color: #999;
  }
}

.unit-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 8rpx;
}
.quotation-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

/* 已选中角色展示样式 */
.selected-roles-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin: 20px 15px 0;
  box-shadow: 0 2px 12px rgba(255, 106, 156, 0.15);
  border: 1rpx solid #f1e2ea;
  
  .selected-roles-header {
    margin-top: 10rpx;
    margin-bottom: 16px;
    text-align: start;
    
    .selected-roles-title {
      display: block;
      font-size: 12px;
      color: #666;
      line-height: 1.4;
    }
    
    .selected-roles-subtitle {
      display: block;
      font-size: 12px;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .selected-roles-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: flex-start;
    
    .selected-role-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 60px;
      
      .role-avatar {
        width: 50px;
        height: 50px;
        border-radius: 25px;
        border: 2px solid #ff6a9c;
        margin-bottom: 6px;
      }
      
      .role-name {
        font-size: 11px;
        color: #333;
        text-align: center;
        line-height: 1.2;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

/* 顶部标题栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  background-color: #fff;
  padding: 0 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 100;

  .back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    
    .icon-back {
      font-size: 24px;
      color: #333;
      font-weight: bold;
    }
  }

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 40px;
  }
}

/* 报价卡片 */
.quotation-card {
  background-color: #fff;
  border-radius: 16px;
  margin: 20px 15px;
  padding: 30px 20px;
  box-shadow: 0 4px 12px rgba(255, 106, 156, 0.1);
  border: 1px solid #f9cde3;

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;

    .header-indicator {
      width: 4px;
      height: 10px;
      background-color: #ff6a9c;
      border-radius: 2px;
      margin-right: 10px;
    }

    .card-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .price-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 15px 0;

    .label-text {
      font-size: 16px;
      color: #333;
      font-weight: 500;
      min-width: 80px;
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      background-color: #fff8fc;
      border: 2px solid #f9cde3;
      border-radius: 12px;
      padding: 12px 15px;
      flex: 1;
      max-width: 200px;
      margin-left: 20px;

      &:focus-within {
        border-color: #ff6a9c;
        box-shadow: 0 0 0 3px rgba(255, 106, 156, 0.1);
      }

      .price-input {
        flex: 1;
        font-size: 18px;
        color: #333;
        text-align: center;
        background-color: transparent;
        border: none;
        outline: none;
        font-weight: 500;
        min-width: 0;

        &::placeholder {
          color: #ccc;
          font-size: 14px;
        }
      }

      .total-price {
        font-size: 18px;
        color: #333;
        font-weight: 600;
        text-align: center;
        flex: 1;
      }

      .unit-text {
        font-size: 14px;
        color: #666;
        margin-left: 8px;
        white-space: nowrap;
      }
    }
  }

  .tips {
    text-align: center;

    .tips-text {
      font-size: 12px;
      color: #999;
      line-height: 1.4;
    }
  }
}

/* 底部按钮区域 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;

  .cancel-btn {
    flex: 1;
    height: 45px;
    border: 1px solid #ddd;
    border-radius: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    margin-right: 10px;
    font-size: 16px;
    color: #333;
    transition: all 0.3s ease;

    &:active {
      background-color: #f5f5f5;
    }
  }

  .confirm-btn {
    flex: 1;
    height: 45px;
    background: linear-gradient(to right, #ff6a9c, #ff9e9e);
    border-radius: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    margin-left: 10px;
    transition: all 0.3s ease;

    &.disabled {
      background: #ccc;
      opacity: 0.6;
    }

    &:not(.disabled):active {
      transform: scale(0.98);
    }
  }
}
</style>
